<template>
	<div>
		<!-- <div>{{ node.name }}</div> -->
		<template v-if="flowNodes && showFlowNodeSelect">
			<div>
				当前状态
				<a-select ref="select" style="width:140px">
					<template #placeholder>
						<div v-if="theStatus === -1">修改中</div>
						<div v-if="theStatus === 0">
							<span v-if="!isMyOk()">审核中</span>
							<span>待审核</span>
						</div>
						<div v-if="theStatus === 1">审核中</div>
						<div v-if="theStatus === 2">已完成</div>
					</template>
					<a-select-option v-for="item in flowNodes" :key="item.id">
						<div>
							{{ item.name }}
							<span></span>
						</div>
						<div>
							<div v-if="item.status === 0">
								<div>
									<a-button type="text" :disabled="disabled">
										<span v-if="isMy() && !isMyOk()">待审核</span>
										<span v-else>审核中</span>
									</a-button>
								</div>
								<div v-if="isMy() && !isMyOk()">
									<a-button type="primary" @click="showOk({status:1})">通过</a-button>
									<!-- v-if="isNotTheOneNode()" -->
									<a-button v-if="stepsIdx > 0" type="primary" danger @click="showBoHui({status:-1})">驳回</a-button>
								</div>
							</div>
							<a-button v-else-if="item.status === 1" type="text" :disabled="disabled" style="color:#87d068">已通过</a-button>

							<template v-else-if="item.status === -1">
								<a-button :style="lastStatus === status?'color:#f50':''" :disabled="disabled" type="text">
									<span>已退回</span>
								</a-button>
							</template>
							<a-button v-else-if="item.status === 2" type="text" :disabled="disabled">已完成</a-button>
						</div>
					</a-select-option>
				</a-select>
			</div>
		</template>
		<template v-if="flowSource && showFlowStatus">
			<!-- <a-button>{{ theStatus }}</a-button> -->
			<!-- 最后操作节点信息 -->
			<!-- <div v-if="nextNode">{{ nextNode.next_node }}</div> -->
			<template v-if="theStatus === 0">
				<a-button v-if="isMy() && !isMyOk()" danger @click="showFlowModel(flowSource)">待审核</a-button>
				<a-button v-else type="text" @click="showFlowModel(flowSource)">审核中</a-button>
			</template>
			<a-button v-else-if="theStatus === 1" type="text" @click="showFlowModel(flowSource)">审核中</a-button>
			<a-button v-else-if="theStatus === -1" type="text" @click="showFlowModel(flowSource)">已退回</a-button>
			<a-button v-else-if="theStatus === 2" type="text" @click="showFlowModel(flowSource)">已完成</a-button>
		</template>
		<template v-else>
			审核中
			<!-- <a-button @click="createFlow">无</a-button> -->
			<!-- <a-button
				type="primary"
				@click="createFlow"
			>待审核</a-button>-->
		</template>
		<a-modal v-model:visible="showBoHuiEdit">
			<template #title>
				<div>驳回</div>
			</template>
			<a-form ref="bohuiFormRef" :model="bohuiForm" v-bind="{labelCol: { style: { width: '70px' } }}">
				<a-form-item v-if="flowNodes.filter((d) => d.no <= stepsIndex).length" label="节点" name="node_id">
					<a-radio-group v-model:value="bohuiForm.node" style="width: 100%">
						<a-row>
							<a-col v-for="item in flowNodes" :key="item.id" :span="8">
								<a-radio v-if="item.no <= stepsIdx" v-model:checked="item.checked" :value="item" @change="changeBohui">{{ item.name }}</a-radio>
							</a-col>
						</a-row>
					</a-radio-group>
				</a-form-item>

				<a-form-item label="退回意见" name="remark">
					<a-textarea v-model:value="bohuiForm.remark" />
				</a-form-item>
			</a-form>
			<!-- </div> -->
			<template #footer>
				<div style="display: flex;justify-content: space-between;">
					<div>
						<a-button @click="showBoHuiEdit=false ; bohuiForm={}">关闭</a-button>
					</div>
					<div>
						<a-button @click="commitBohui">提交</a-button>
					</div>
				</div>
			</template>
		</a-modal>

		<a-modal v-model:visible="showOkEdit">
			<template #title>
				<div>审核通过</div>
			</template>
			<a-form ref="okEditFormRef" :model="okEditForm" v-bind="{labelCol: { style: { width: '70px' } }}">
				<a-form-item v-if="bohuiNodes && bohuiNodes.length>0" label="节点" name="node_id">
					<a-radio-group v-model:value="okEditForm.node" style="width: 100%">
						<a-row>
							<a-col v-for="item in bohuiNodes" :key="item.id" :span="8">
								<a-radio v-model:checked="item.checked" :value="item" @change="changeOk">{{ item.name }}</a-radio>
							</a-col>
						</a-row>
					</a-radio-group>
				</a-form-item>

				<a-form-item label="备注" name="remark">
					<a-input v-model:value="okEditForm.remark" />
				</a-form-item>
			</a-form>
			<!-- </div> -->
			<template #footer>
				<div style="display: flex;justify-content: space-between;">
					<div>
						<a-button @click="showOkEdit=false ; okEditForm={}">关闭</a-button>
					</div>
					<div>
						<a-button @click="commitOk">确认</a-button>
					</div>
				</div>
			</template>
		</a-modal>

		<a-modal v-model:visible="visible" :body-style="{height:'400px',overflowY: 'auto'}" :closable="false" :width="400">
			<template #title>
				<!-- <template v-if="activeKey == '1'"> -->
				<div v-if="flowSource">{{ flowSource.name!==null?flowSource.name:'流程详情' }}</div>
			</template>

			<template v-if="flowSource">
				<a-steps :current="stepsIdx" direction="vertical">
					<a-step v-for="item in flowNodes" :key="item.id">
						<template #title>
							<div>
								{{ item.name }}
								<span @click="toDetail(item)">详情</span>
							</div>
						</template>
						<template #description>
							<div>
								<!-- {{ item }} -->
								<div v-if="item.status === 0">
									<div>
										<a-button danger :disabled="disabled">
											<span v-if="isMy() && !isMyOk()">待审核</span>
											<span v-else>审核中</span>
										</a-button>
									</div>
								</div>
								<a-button v-else-if="item.status === 1" :disabled="disabled" style="color:#87d068">已通过</a-button>
								<template v-else-if="item.status === -1">
									<a-button :style="lastStatus === status?'color:#f50':''" danger :disabled="disabled">
										<span>已退回</span>
									</a-button>
								</template>
								<a-button v-else-if="item.status === 2" type="dashed" danger :disabled="disabled">已完成</a-button>
							</div>
							<div v-if="item.node.remark">备注:{{ item.node.remark }}</div>
							<div v-else-if="item.remark">备注:{{ item.remark }}</div>
						</template>
					</a-step>
				</a-steps>
			</template>
			<!-- </div> -->
			<template #footer>
				<div style="display: flex;justify-content: space-between;">
					<div>
						<a-button @click="handleCancel">取消</a-button>

						<a-button v-if="authAct('refresh')" @click="run">刷新</a-button>
					</div>
					<div v-if="!isMyOk()">
						<!-- <a-button @click="updateStatusOk">手动完成</a-button> -->
						<span v-if="isMy()">
							<a-button type="primary" @click="showOk({status:1})">通过</a-button>
							<!-- v-if="isNotTheOneNode()" -->
							<a-button v-if="stepsIdx >= 0" type="primary" danger @click="showBoHui({status:-1})">驳回</a-button>
						</span>
					</div>
				</div>
			</template>
		</a-modal>
	</div>
</template>
<script setup>
/**
 * 项目审核状态操作
 */
import { ref, watch, onMounted, getCurrentInstance, reactive } from "vue";
import { post, treeToList } from "../utils";
import { useRequest } from "vue-request";
import { useRouter } from "vue-router";
import router from "../router";
import dayjs from "dayjs";
const { proxy } = getCurrentInstance();

const roles = ref();
const flowStatus = ref();
const flowSource = ref();
const flowNodes = ref();
const flowTypeSource = ref();
const state = reactive({ node_ids: 0 });
const activeKey = ref("2");
const showEdit = ref(true);
flowStatus.value = [
	{ status: -1, name: "退回" },
	{ status: 0, name: "待审核" },
	{ status: 1, name: "通过" },
	{ status: 2, name: "完成" }
];
const formType = ref();
// 表单输入框 禁用状态
const inputDisable = (node, type) => {
	var disable = {
		name: {
			create: true,
			update: true
		},
		status: {
			create: true,
			update: true
		},
		type_id: {
			create: true,
			update: true
		},
		node_ids: {
			create: false,
			update: true
		},
		module_id: {
			create: true,
			update: true
		},
		item_id: {
			create: true,
			update: true
		}
	};
	if (node in disable && type in disable[node] && disable[node][type]) {
		return true;
	}
	return false;
};
// 最后的节点 自己是否已操作完毕
const isMyOk = () => {
	var lastNode = getflowNodeLine(true);

	if (!lastNode.next_node || lastNode.next_node.status !== 0) {
		return false;
	}
	// if (!flowSource.value.flowType.flowTypeNodes) {
	// 	console.log("鉴权缺少参数");
	// }
	// console.log(lastNode);
	var users = lastNode.next_node.users;
	if (users) {
		var uids = users.map(e => e.id);
		// console.log(uids);
		return proxy.$auth.isUsers(uids) || false;
	}
};
const isMy = () => {
	var lastNode = getflowNodeLine(true);
	if (!lastNode.next_node || lastNode.next_node.status !== 0) {
		return false;
	}
	if (!flowSource.value.flowType.flowTypeNodes) {
		//console.log("鉴权缺少参数");
	}
	var theNode = flowSource.value.flowType.flowTypeNodes.find(e => {
		return e.no === lastNode.next_node.no;
		// roles
	});
	if (theNode && theNode.roles) {
		var roles = theNode.roles.map(e => e.id);
		// console.log(roles);
		return proxy.$auth.isRole(roles) || false;
	}
};
const onNodeStatus = e => {
	// console.log(e);
};
const bohuiForm = ref({});
const commitBohui = () => {
	var data = {
		status: -1,
		remark: bohuiForm.value.remark,
		no: bohuiForm.value?.node?.no || 0
	};
	updateNodeStatus(data);
};
const changeBohui = e => {
	bohuiForm.value = { ...bohuiForm.value, node_id: e.target.value.id };
	// console.log(bohuiForm.value);
};
const showBoHuiEdit = ref();
const showBoHui = () => {
	showBoHuiEdit.value = true;
	visible.value = false;
};
const bohuiNodes = ref();
const isBohui = ref();
const getBohuiNodes = () => {
	var myNodes = [];
	isBohui.value = flowNodes.value.findIndex(e => e.status === -1);
	// 是驳回的
	if (isBohui.value > -1) {
		var thenum = stepsIdx.value + 1;
		for (let i = 0; i < flowNodes.value.length; i++) {
			if (flowNodes.value[i].no > thenum) {
				myNodes.push(flowNodes.value[i]);
			}
			if (flowNodes.value[i].status === -1) {
				break;
			}
		}
		// 不是驳回的不能选
	}
	bohuiNodes.value = myNodes;
	// flowNodes.value.filter((e) => {});
	// console.log(flowNodes.value);
	// console.log(myNodes);
	return myNodes;
	// item.no > stepsIdx
};
const okEditFormRef = ref();
const okEditForm = ref({});
const showOkEdit = ref();
const commitOk = () => {
	var data = {
		status: 1,
		remark: okEditForm.value.remark
	};
	if (okEditForm.value.node && okEditForm.value.node.no) {
		data.no = okEditForm.value.node.no;
	} else {
		data.no = stepsIdx.value + 1;
	}
	// console.log(okEditForm.value);
	updateNodeStatus(data);
	// console.log(okEditForm.value);
};
const changeOk = e => {
	okEditForm.value = { ...okEditForm.value, node_id: e.target.value.id };
	// console.log(okEditForm.value);
};
const showOk = () => {
	getBohuiNodes();
	showOkEdit.value = true;
	visible.value = false;
};
// 用户操作权限
// node_ids
const authAct = act => {
	if (act === "update") {
		return true;
	} else if (act === "create") {
		return true;
	}
	return true;
};
// 必填flowId 或者 (moduleId,itemId)
const props = defineProps({
	disabled: {
		type: Boolean,
		required: false,
		default: true
	},
	// 默认不显示 搜索框
	showFlowNodeSelect: {
		type: Boolean,
		required: false,
		default: false
	},
	// 默认显示按钮
	showFlowStatus: {
		type: Boolean,
		required: false,
		default: true
	},
	// 审批项id
	showFormItem: {
		type: Object,
		required: false,
		default: () => {
			return {
				remark: true,
				name: false,
				node_ids: true
			};
		}
	},
	flowId: {
		type: Number,
		required: false,
		default: 0
	},
	// 模块标识
	moduleId: {
		type: String,
		required: false,
		default: ""
	},
	// 模块下内容id
	itemId: {
		type: Number,
		required: false,
		default: 0
	}
});

//定义emit
const emit = defineEmits(["update:flowId", "update:moduleId", "update:itemId", "change"]);
const route = useRouter();
const toDetail = e => {
	//进场确认
	route.push({
		name: "FlowDetail",
		query: { node_id: e.node.id, flow_id: e.node.flow_id }
	});
};
const getFlowTypeList = async moduleId => {
	// flowTypeSource.value = flowSource.value.flowType;
	return post("flow/getFlowTypeList", {
		module_id: moduleId || props.moduleId || ""
	}).then(({ data }) => {
		emit("change", { act: "flowTypeList", data });
		flowTypeSource.value = data[0];
	});
};
const params = ref();

const theStatus = ref(-9);
const initflowTypeSource = (typeid, moduleId = "") => {
	var e = flowTypeSource.value;
	// const data = flowTypeSource.value.map((e) => {
	if (e.id === typeid || moduleId === e.module_id) {
		// console.log(e);
		// if (e.roles) {
		// 	// var depts = e.roles;
		// 	roles.value = depts;
		// }
		params.value.type_id = e.id;
		params.value.module_id = e.module_id;
		if (!formState.value.name) {
			formState.value.name = e.name;
		}
		formState.value.type_id = e.id;
		formState.value.module_id = e.module_id;
		return e;
	}
	// });
};
const visible2 = ref(false);
onMounted(async () => {
	// console.log(props);
	await getFlowTypeList(props.moduleId);

	if (props.flowId !== 0) {
		params.value = { id: props.flowId };
		run();
	} else if (props.moduleId !== "" && props.itemId !== 0) {
		params.value = { module_id: props.moduleId, item_id: props.itemId };
		initflowTypeSource(null, props.moduleId);

		run();
	} else {
		//console.log("未传值");
	}
});
const stepsIdx = ref(0);
const visible = ref(false);
const formRef = ref();
const formState = ref({
	name: null,
	type_id: null,
	module_id: null
});

const changeTypeId = item => {
	const typeid = item.target.value;
	initflowTypeSource(typeid);
};
const flowTypeNodes = ref();
const run = () => {
	post("flow/info", params.value).then(data => {
		// console.log(data, params.value);
		if (!data.id) {
			//console.log("数据不存在为您创建");
			return;
		}
		if (props.flowId !== data.id) {
			emit("update:flowId", data.id);
		}
		if (props.itemId !== data.item_id) {
			emit("update:itemId", data.item_id);
		}
		if (props.moduleId !== data.module_id) {
			emit("update:moduleId", data.module_id);
		}
		var idx = 0;
		flowNodes.value = data.flowNodes.filter(e => {
			idx++;
			e.idx = idx;
			e.update_time = dayjs(e.update_time).format("YYYY-MM-DD HH:mm:ss");
			return e;
		});

		if (data.flowType) {
			// console.log(data.flowType);
			// 所有要审批的节点
			var depts = data.flowType.flowTypeNodes;
			// var depts = roles.value;
			depts = depts.map(item => {
				// 默认值不能是0
				item.status = -9;
				// item.flowNodes = [];
				// item.roles  这个节点下的所有角色
				item.nodeStatus = -9;
				flowNodes.value.map(flownode => {
					if (flownode.no === item.no) {
						item.node = { ...flownode };
						item.status = flownode.status;
						// item.flowNodes.push(flownode);
						// if (item.status !== 0) {
						// 	item.status = flownode.status;
						// }
					}
					// if (flownode.role_id === item.id) {
					// 	item.flowNodes.push(flownode);
					// 	if (item.status !== 0) {
					// 		item.status = flownode.status;
					// 	}
					// }
				});
				return item;
			});
			// console.log(flowNodes.value);
			flowNodes.value = depts;
			// console.log(depts)
			// roles.value = depts;
			data.flowType.roles = depts;
		} else {
			data.flowType = {};
			// roles.value = {};
			data.flowType.roles = {};
		}

		flowSource.value = data;
		var lastNode = getflowNodeLine(true);
		if (flowSource.value && flowSource.value.status === 2) {
			theStatus.value = 2;
			stepsIdx.value = lastNode.node.no;
		} else if (lastNode && lastNode.next_node) {
			theStatus.value = lastNode.next_node.status;
			stepsIdx.value = lastNode.next_node.no - 1;
		}

		emit("change", { act: "flowInfoData", data: data });
		// console.log(flowSource.value)
		visible2.value = true;
	});
};
// 不是第一个节点
const isNotTheOneNode = ref(true);

const updateNodeStatus = ({ status, remark, no }) => {
	var lastNode = getflowNodeLine(true);
	if (!lastNode) {
		return;
	}
	proxy.$message.destroy();
	const params = {
		status: status,
		id: lastNode.next_node_id,
		no: no || stepsIdx.value + 1,
		remark
	};

	post("flow/updateNodeStatus", params)
		.then(() => {
			proxy.$message.success("更新成功", 1);
			visible.value = false;
			showBoHuiEdit.value = false;
			showOkEdit.value = false;
			run();
			emit("change", { act: "updateStatus", stisRoleatus: 1 });
		})
		.catch(err => {
			proxy.$message.error(err);
		});
};
const changeFlowNodeTmp = e => {
	if (e.act === "setData") {
		//console.log("setdata");
		flowSource.value = e.data;
	} else if (e.act === "onMounted") {
		//console.log(e.act);
		// flowNodeRef.value.setData(flowSource.value);
	}
	// emit("change", e);
};
const nextNode = ref({ status: -9 });
const thisNode = ref({ status: -9 });
// const flowNodes = ref();
const getflowNodeLine = (isLast = false) => {
	if (!flowSource.value) {
		return;
	}
	//console.log(flowSource.value);

	var flowLines = flowSource.value.flowLines.map(e => {
		flowSource.value.flowNodes.map(e2 => {
			// 最后一个节点信息
			if (e.next_node_id === e2.id) {
				e.next_node = e2;
				// 主线状态 用最后那个节点的状态
				// console.log(e2);
				e.node_status = e2.status;
			}
			// // 当前节点信息
			if (e.node_id === e2.id) {
				e.node = e2;
			}
		});
		return e;
	});
	// console.log(flowLines);
	if (isLast) {
		nextNode.value = flowSource.value.flowLines[flowSource.value.flowLines.length - 1];
		// console.log(nextNode.value);
		return nextNode.value;
	}
	return flowSource.value.flowLines;
};
const showFlowModel = async record => {
	formRef.value?.clearValidate();
	visible.value = true;

	const data = { ...record };
	// var depts = record.flowNodes;
	if (data.node_ids) {
		state.node_ids = data.node_ids.split(",").map(d => parseInt(d));
	}
	formState.value = data;

	formType.value = formState.value.id ? "update" : "create";
	// console.log(formState.value);
	initflowTypeSource(data.type_id, data.module_id);
};
const createFlow = () => {
	params.value.status = 0;
	showFlowModel(params.value);
};
const formValidate = () => {
	return new Promise(resolve => {
		params.value = { ...formState.value };
		if (state.node_ids) {
			params.value.node_ids = state.node_ids;
			// params.value.node_ids = state.node_ids.join(",");
		}
		formRef.value
			.validate()
			.then(() => {
				proxy.$message.destroy();
				resolve(params.value);
			})
			.catch(err => {
				//console.log(err);
				// proxy.$message.error(err);
			});
	});
};
// 用户权限创建接口
const createFlowApi = () => {
	if (!authAct("create", "flow:create")) {
		proxy.$message.error("创建权限不够");
		return;
	}
	formValidate().then(param => {
		post("flow/userCreate", { ...param })
			.then(() => {
				proxy.$message.success("行业信息提交成功", 1);
				visible.value = false;
				showBoHuiEdit.value = false;
				// expandedRowKeys.value.push(params.parent_id);
				emit("change", { act: "createFlow", status: 1 });
				run();
			})
			.catch(err => {
				proxy.$message.error(err);
			});
	});
};
const updateStatusOk = () => {
	var count = flowSource.value.flowNodes.findIndex(e => {
		return e.status === 0;
	});
	if (count > -1) {
		proxy.$message.error("对不起，有节点处于待审核状态");
		return;
	}
	// if (flowSource.value.status !== 1) {
	// 	proxy.$message.error("有未完成状态，或已完成");
	// 	return;
	// }

	post("flow/updateStatusOk", { id: flowSource.value.id })
		.then(() => {
			emit("change", { act: "updateStatus", flowSource });
			proxy.$message.success("更新成功", 1);
			run();
			visible.value = false;
			showBoHuiEdit.value = false;
		})
		.catch(err => {
			proxy.$message.error(err);
		});
};
// 用户权限更新接口
const updateFlowApi = () => {
	if (!authAct("update", "flow:update")) {
		proxy.$message.error("更新权限不够");
		return;
	}
	formValidate().then(param => {
		post("flow/userUpdate", { ...param, status: 0 })
			.then(() => {
				proxy.$message.success("行业信息提交成功", 1);
				visible.value = false;

				// expandedRowKeys.value.push(params.parent_id);
				emit("change", { act: "updateFlow", status: 1 });
				run();
			})
			.catch(err => {
				proxy.$message.error(err);
			});
	});
};

// 管理员权限 创建或更新
const saveFlow = () => {
	formValidate().then(e => {
		post("flow/save", { ...params.value })
			.then(() => {
				proxy.$message.success("行业信息提交成功", 1);
				visible.value = false;

				// expandedRowKeys.value.push(params.parent_id);
				emit("change", { act: "flowSave", status: 1 });
				run();
			})
			.catch(err => {
				proxy.$message.error(err);
			});
	});
};
watch(visible, value => {
	// console.log(value);
	// if (value) {
	// 	console.log(flowNodeRef.value);
	// 	// console.log(flowSource.value);
	// 	// console.log(roles.value);
	// 	if (flowNodeRef.value) {
	// 		console.log(flowSource.value);
	// 		flowNodeRef.value.setData(flowSource.value);
	// 	}
	// }
	if (value) formRef.value?.clearValidate();
});
const handleCancel = () => {
	visible.value = false;
};
const initData = () => {
	run();
};
const flowNodeRef = ref();
const setData = data => {
	flowSource.value = data;
};
const getData = () => {
	return { ...flowSource.value };
};
defineExpose({
	getData,
	initData,
	setData
});
// run();
</script>